local ServerOHOH = _G.ServerOHOH;
local M = ServerOHOH.class.new(script, ServerOHOH.files.BaseComponent());
local CommonOHOH = _G.CommonOHOH;
local PetTool=_G.CommonOHOH.load.PetTool();

function M.new(self,...)
	return M(self,...);
end;

function M.ctor(self, parent)
	M.super.ctor(self, parent);
	local petFolder= Instance.new("Folder",self.parent.main_inst)
	petFolder.Name="PETS"
	self.petParent=petFolder
	self.Database= self.parent.player:GetComponent(ServerOHOH.load.Server_PlayerDataComponent());
	self.AttachmentList={}

	self.parent.player.PetEuqipUpdateEvent:Connect(function()
		self:UpdatePets()
	end)
	self:UpdatePets()
end;

function M.dtor(self)
	M.super.dtor(self);
end;

function M.UpdatePets(self)
	local now=self.Database:GetData("pets").equip.__real
	if self.oldEquip then
		local isEqule=true
		for k,v in pairs(now) do
			if not(self.oldEquip[k] and self.oldEquip[k]==v) then
				isEqule=false
				break
			end
		end
		if isEqule then
			for k,v in pairs(self.oldEquip) do
				if not(now[k] and now[k]==v) then
					isEqule=false
					break
				end
			end
		end
		if isEqule then
			return
		end
	end

	self.petParent:ClearAllChildren()

	task.wait(0.5)

	for k,v in pairs(self.AttachmentList) do
		v:Destroy()
	end
	self.AttachmentList={}

	self.oldEquip={}
	local objList={}

	for k,v in pairs(now) do
		self.oldEquip[k]=v
		for i=1,v do
			local model= PetTool.GetPetModelByPetId(k)
			table.insert(objList,model)
		end
	end

	if #objList==0 then
		return
	end

	local posList=workspace.Pets.Pos:FindFirstChild(#objList):GetDescendants()

	for k,v in pairs(objList) do
		
		local att= Instance.new("Attachment",self.parent:GetRootPart_Loop())
		att.CFrame=posList[k].Value
		table.insert(self.AttachmentList,att)
		-- local cf=self.parent:GetCFrame():ToWorldSpace(posList[k].Value)  
		v:SetPrimaryPartCFrame(att.WorldCFrame)
		task.wait()
		v.Parent=self.petParent

		local AnchorPart=v:FindFirstChild("anchor")

		AnchorPart.Anchored=false
		AnchorPart.CanTouch=false
		AnchorPart.CanCollide=false
		AnchorPart.Massless=true

		local rotateCtrl=AnchorPart:FindFirstChild("AlignOrientation")
		local posCtrl=AnchorPart:FindFirstChild("AlignPosition")
		rotateCtrl.Attachment1=att
		posCtrl.Attachment1=att

		for _,p in pairs(v:GetDescendants()) do
			if p:IsA("BasePart") and p.Name~="anchor" then
				p.Anchored=false
				p.CanTouch=false
				p.CanCollide=false
				p.Massless=true
				local w= Instance.new("WeldConstraint",p)
				w.Part0=p
				w.Part1=AnchorPart
			end
		end
		rotateCtrl.Enabled=true
		posCtrl.Enabled=true
	end

end




return M